package keeper

import (
	"errors"
	"etcdkeeper/session"
	_ "etcdkeeper/session/providers/memory"
	"flag"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"
)

// 变量定义
var (
	separator  = ""
	assetsPath = "./assets"

	Host = flag.String("h", "0.0.0.0", "host name or ip address")
	Port = flag.Int("p", 8080, "port")

	sep     = flag.String("sep", "/", "separator")
	usetls  = flag.Bool("usetls", false, "use tls")
	cacert  = flag.String("cacert", "", "verify certificates of TLS-enabled secure servers using this CA bundle")
	cert    = flag.String("cert", "", "identify secure client using this TLS certificate file")
	keyfile = flag.String("key", "", "identify secure client using this TLS key file")
	useAuth = flag.Bool("auth", false, "use auth")

	rootUsers   = make(map[string]*userInfo) // host:rootUser
	rootUesrsV2 = make(map[string]*userInfo) // host:rootUser

	sessmgr *session.Manager
	mu      sync.Mutex
)

type userInfo struct {
	host   string
	uname  string
	passwd string
}

// Init 初始化
func Init() error {
	separator = *sep

	wd, err := os.Executable()
	if err != nil {
		log.Println(err)
		return err
	}

	info, err := os.Stat(assetsPath)
	if err != nil {
		log.Println(err)
		return err
	}

	if info.IsDir() == false {
		assetsPath = filepath.Dir(wd) + "/assets"
	}

	info, err = os.Stat(assetsPath)
	if err != nil {
		log.Println(err)
		return err
	}

	if info.IsDir() == false {
		log.Println("assetsPath is error, ", assetsPath)
		return errors.New("assetsPath is error")
	}

	// Session management
	sessmgr, err = session.NewManager("memory", "_etcdkeeper_session", 86400)
	if err != nil {
		log.Println(err)
		return err
	}

	time.AfterFunc(86400*time.Second, func() {
		sessmgr.GC()
	})

	return nil
}
